package com.zhijian.warehouse.manage.service;

import com.zhijian.warehouse.manage.entity.po.User;
import com.zhijian.warehouse.manage.entity.vo.request.LoginVo;
import com.zhijian.warehouse.manage.entity.vo.response.AuthVo;
import com.zhijian.warehouse.manage.enums.ResponseEnum;
import com.zhijian.warehouse.manage.exception.BusinessCommonException;
import com.zhijian.util.EncryptUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.Objects;

/**
 * @author HCG
 * @version 1.0
 * @date 2023-05-05
 */
public abstract class LoginAbstract {

    @Autowired
    private UserService userService;

    /**
     * 登录
     *
     * @param vo
     * @return
     */
    public abstract AuthVo login(LoginVo vo);

    /**
     * 用户登出
     *
     * @param token 登录token
     * @return
     */
    public abstract boolean logout(String token);

    /**
     * 修改密码
     *
     * @param id
     * @param oldPassword
     * @param newPassword
     * @return
     */
    public boolean changePassword(Long id, String oldPassword, String newPassword) {
        User person = userService.selectById(id);
        if (Objects.isNull(person)) {
            throw new BusinessCommonException(ResponseEnum.LOGIN_WRONG);
        }
        //校验：账号密码正确性校验
        String pwdMd5 = EncryptUtil.password(oldPassword, person.getSalt());
        if (!pwdMd5.equals(person.getPassword())) {
            throw new BusinessCommonException(ResponseEnum.LOGIN_WRONG);
        }
        userService.updateByPrimaryKeySelective(User.builder()
                .id(id)
                .password(EncryptUtil.password(newPassword, person.getSalt()))
                .updateTime(new Date())
                .build());
        return true;
    }
}
